package com.iot.ic.modules.dao.impl;

import com.iot.ic.common.dao.BaseDaoImpl;
import com.iot.ic.modules.dao.AmountDao;
import com.iot.ic.modules.model.Accounts;
import com.iot.ic.modules.model.Amounts;
import com.iot.ic.modules.model.User;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@Service("amountDao")
public class AmountDaoImpl extends BaseDaoImpl implements AmountDao {
    @Override
    public Amounts findAmountByUid(Integer userId) throws Exception {
        EntityManager em = super.getEntiyManager();
        Query query = em.createNativeQuery(" select t.*  from t_amounts t where t.user_id=?1 ", Amounts.class);
        query.setParameter(1, userId);
        List list = query.getResultList();
        Object outO;
        if (list == null || list.size() ==0) {
            outO = null;
        } else {
            outO = list.get(0);
        }
        em.close();
        return (Amounts) outO;
    }

    @Override
    public boolean updateAmountState(Integer userId, Integer state) {
        StringBuffer sql = new StringBuffer();
        sql.append(" update t_amounts as t set t.state=").append(state);
        sql.append(" where t.user_id = ").append(userId);
        EntityManager em = this.getEntiyManager();
        em.getTransaction().begin();
        Query query = em.createNativeQuery(sql.toString());
        int result = query.executeUpdate();
        try {
            em.getTransaction().commit();
            return result>0;
        } catch (Exception e) {
            em.getTransaction().rollback();
            throw e;
        } finally {
            em.close();
        }
    }

    @Override
    public List<Accounts> findAccountByUid(Integer userId) throws Exception {
        EntityManager em = super.getEntiyManager();
        Query query = em.createNativeQuery(" select t.* from t_accounts t where t.user_id=?1 order by addtime desc ", Accounts.class);
        query.setParameter(1, userId);
        List list = query.getResultList();
        em.close();
        return list;
    }
}
